<template>
  <div class="container fade-in">
    <div class="header">
      <h2 class="section-title">门店管理</h2>
    </div>

    <div class="card filters slide-up" style="animation-delay: 0.2s">
      <div class="filter-row">
        <label class="filter-label">门店名称</label>
        <input v-model="filters.key" class="input flex-1" placeholder="输入名称进行搜索" @input="debouncedSearch" />
        <button class="btn secondary" @click="resetFilters">重置</button>
      </div>
    </div>

    <div class="card table-container slide-up" style="animation-delay: 0.3s">
      <div class="table-header">
        <h3>门店列表</h3>
        <div class="table-actions">
          <button class="btn secondary" @click="loadStores">
            <span class="icon">🔄</span>
            刷新
          </button>
        </div>
      </div>

      <table class="table">
        <thead>
          <tr>
            <th>门店编码</th>
            <th>名称</th>
            <th>联系人</th>
            <th>联系电话</th>
            <th>启用状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading" class="loading-row">
            <td colspan="7" class="loading">
              <div class="spinner"></div>
              加载中...
            </td>
          </tr>
          <tr v-else-if="stores.length === 0" class="empty-row">
            <td colspan="7" class="empty">暂无数据</td>
          </tr>
          <template v-else>
            <tr v-for="s in stores" :key="s.id" class="data-row">
              <td>{{ s.storeCode || '-' }}</td>
              <td>{{ s.name }}</td>
              <td>{{ s.contactPerson || '-' }}</td>
              <td>{{ s.contactPhone || '-' }}</td>
              <td>
                <span class="badge" :class="enableBadge(s.enableStatus)">{{ enableText(s.enableStatus) }}</span>
              </td>
              <td>{{ formatDate(s.creationTime) }}</td>
              <td>
                <div class="actions">
                  <router-link :to="`/stores/detail/${s.id}`" class="btn small secondary" title="查看详情">
                    <span class="icon">👁️</span>
                    详情
                  </router-link>
                </div>
              </td>
            </tr>
          </template>
        </tbody>
      </table>

      <div v-if="pagination.total > 0" class="pagination">
        <div class="pagination-info">
          共 {{ pagination.total }} 条记录，第 {{ pagination.current }} / {{ Math.ceil(pagination.total / pagination.pageSize) }} 页
        </div>
        <div class="pagination-controls">
          <button class="btn secondary sm" :disabled="pagination.current <= 1" @click="changePage(pagination.current - 1)">上一页</button>
          <button class="btn secondary sm" :disabled="pagination.current >= Math.ceil(pagination.total / pagination.pageSize)" @click="changePage(pagination.current + 1)">下一页</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { isSuccess } from '../services/types'
import { StoreService, type StoreResponse } from '../services/store'

const loading = ref(false)
const stores = ref<StoreResponse[]>([])
const filters = reactive({ key: '' })
const pagination = reactive({ current: 1, pageSize: 10, total: 0 })

function debounce<T extends (...args: any[]) => void>(fn: T, delay = 300) {
  let t: any
  return (...args: any[]) => {
    clearTimeout(t)
    t = setTimeout(() => fn(...args), delay)
  }
}

const debouncedSearch = debounce(() => {
  pagination.current = 1
  loadStores()
}, 300)

function enableText(s?: number) {
  if (s === 1) return '启用'
  if (s === 0) return '禁用'
  return '未知'
}
function enableBadge(s?: number) {
  return s === 1 ? 'active' : 'inactive'
}

function formatDate(v?: string) {
  if (!v) return '-'
  try { return new Date(v).toLocaleString('zh-CN') } catch { return v }
}

async function loadStores() {
  loading.value = true
  try {
    const res = await StoreService.getStoreList(pagination.current, pagination.pageSize, filters.key)
    if (isSuccess(res) && res.data) {
      stores.value = res.data.data || []
      pagination.total = res.data.total || stores.value.length
    } else {
      stores.value = []
      pagination.total = 0
      console.warn('获取门店列表失败:', res?.message)
    }
  } catch (e) {
    console.error('接口异常:', e)
  } finally {
    loading.value = false
  }
}

function resetFilters() {
  filters.key = ''
  pagination.current = 1
  loadStores()
}

function changePage(p: number) {
  pagination.current = p
  loadStores()
}

onMounted(loadStores)
</script>

<style scoped>
.header { display: flex; align-items: center; justify-content: space-between; }
.filters { padding: var(--space-4); }
.filter-row { display:flex; align-items:center; gap: var(--space-3); }
.filter-label { color: var(--text-secondary); }
.flex-1 { flex: 1; min-width: 240px; }
.table { width: 100%; border-collapse: collapse; }
.table th, .table td { padding: 12px; border-bottom: 1px solid var(--border); }
.badge { padding: 2px 8px; border-radius: var(--radius); font-size: var(--text-sm); }
.badge.active { background: var(--primary-50); color: var(--primary-700); }
.badge.inactive { background: var(--bg-secondary); color: var(--text-secondary); }
.table-row:hover { background: var(--bg-secondary); }
.loading-state, .empty-state { text-align: center; padding: var(--space-6); color: var(--text-secondary); }
.pagination { display: flex; align-items: center; justify-content: space-between; padding: var(--space-4); }
.table-container { overflow-x: auto; }
.table-header { display:flex; align-items:center; justify-content:space-between; padding: var(--space-4); }
.table-actions { display:flex; gap: var(--space-3); }
.data-row:hover { background: var(--bg-secondary); }
.loading-row .loading, .empty-row .empty { text-align: center; padding: var(--space-4); color: var(--text-secondary); }
.spinner { width: 16px; height: 16px; border: 2px solid var(--border); border-top-color: var(--primary-600); border-radius: 50%; display:inline-block; animation: spin 0.8s linear infinite; margin-right: 8px; }
@keyframes spin { to { transform: rotate(360deg); } }
</style>

